﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LapvComponent;
using log4net;
using System.Configuration;
using LapvBussiness;

namespace Lapv.Account
{
    public partial class PermissionAdd : System.Web.UI.Page
    {

        public int PMId = 0;
       
        public string domainStyle = ConfigLapv.Instance.DomainStyle;
        private static readonly ILog log = LogManager.GetLogger(typeof(Lapv).Name); 
        public string domain =ConfigLapv.Instance.DomainAdmin;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (Request.Params["PMId"] != null)
            {
                int.TryParse(Request.Params["PMId"].Trim().Replace("'", ""), out PMId);

            }
            string curUrl = Request.RawUrl.ToString();
            //ProviderAdmin.CheckAuthen(curUrl, 9);

            if (Page.IsPostBack) return;
            loadData();

        }
        public void functionGridNews(object source, DataGridCommandEventArgs evt)
        {
            switch (evt.CommandName.Trim().ToLower())
            { 
                case "edit":
                    try
                    {
                        if (evt.CommandArgument.ToString() != null)
                        {
                            PMId = Convert.ToInt32(evt.CommandArgument);
                            Response.Redirect(domain + "Account/PermissionAdd.aspx?PMId=" + Convert.ToString(PMId));
                        }
                    }
                    catch (Exception)
                    {
                        return;
                    }
                    break;


            }
        }
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                using (lapvEntities db = new lapvEntities())
                {
                    ImageButton imageButton = (ImageButton)sender;
                    int id = int.Parse(imageButton.CommandArgument);
                    if (id > 0)
                    {


                        permission objOld = db.permissions.Where(ec => ec.id == id).FirstOrDefault();
                        if (objOld != null)
                        {
                            db.DeleteObject(objOld);
                            db.SaveChanges();
                            loadData();
                            ((Lapv)this.Master).MessageInfomational = "Xóa Permission thành công!";
                            loga("Xóa Permission thành công! Mã Permission: " + objOld.id, "PERMISSION_DELETE");

                        }

                        else
                        {
                            ((Lapv)this.Master).MessageError = "Không tồn tại dữ liệu muốn xóa!";
                            loga("Xóa Permission không thành công do không tồn tại đối tượng này! Mã Permission:" + id, "PERMISSION_DELETE");

                            loadData();
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }
        protected void btnEdit_Click(object sender, EventArgs e)
        {

            try
            {



                using (lapvEntities db = new lapvEntities())
                {

                    if (PMId > 0)
                    {
                        permission obj = db.permissions.Where(ec => ec.id == PMId).FirstOrDefault();
                        if (obj != null)
                        {
                            obj.name = txtName.Text;
                            obj.description = txtContent.Text;
                            db.ApplyCurrentValues(obj.EntityKey.EntitySetName, obj);
                            db.SaveChanges();



                            permission_pages newobj = null;
                         //  List<role_permission> oldRP = obj.role_permission.ToList();
                           // if (oldRP.Count > 0)
                           // {
                           //     foreach (role_permission it in oldRP)
                           //     {
                           //         //obj.role_permission.Remove(it);
                           //         db.DeleteObject(it);
                           //     }

                           //     db.SaveChanges();
                           // }
                            bool kt = false;
                            foreach (ListItem it in chkPermission.Items)
                            {
                                if (it.Selected == true)
                                {
                                    newobj = new permission_pages();
                                    newobj.per_pagesReference.EntityKey = new System.Data.EntityKey("lapvEntities.role", "id", PMId);
                                    newobj.permissionReference.EntityKey = new System.Data.EntityKey("lapvEntities.permission", "id",it.Value);
                                    obj.permission_pages.Add(newobj);
                                    if (kt == false) kt = true;
                                }
                            }
                            if (kt == true)
                            {
                                db.ApplyCurrentValues(obj.EntityKey.EntitySetName, obj);
                                db.SaveChanges();
                            }
                            ((Lapv)this.Master).MessageError = "Sửa Permission thành công! Mã Permission: " + obj.id;
                            loga("Sửa Permission thành công! Mã Permission: " + obj.id, "PERMISSION_EDIT");

                            Response.Redirect(domain + "Account/PermissionAdd.aspx");
                        }
                    }
                    else
                    {
                        permission obj = new permission();
                        obj.name = txtName.Text;
                        obj.description = txtContent.Text;
                        obj.type = 0;
                        db.AddTopermissions(obj);
                        db.SaveChanges();
                        PMId = obj.id;

                        permission_pages newobj = null;
                        bool kt = false;
                        foreach (ListItem it in chkPermission.Items)
                        {
                            if (it.Selected == true)
                            {
                                newobj = new permission_pages();

                                newobj.per_pagesReference.EntityKey = new System.Data.EntityKey("lapvEntities.per_pages", "id", PMId);
                                newobj.permissionReference.EntityKey = new System.Data.EntityKey("lapvEntities.permission", "id", short.Parse(it.Value));

                                obj.permission_pages.Add(newobj);
                                if (kt == false) kt = true;
                            }
                        }
                        if (kt == true)
                        {
                            db.ApplyCurrentValues(obj.EntityKey.EntitySetName, obj);
                            db.SaveChanges();
                        }

                        ((Lapv)this.Master).MessageError = "Thêm Permission thành công! Mã Permission: " + obj.id;
                        loga("Thêm Permission thành công! Mã Permission: " + obj.id, "PERMISSION_ADD");
                        Response.Redirect(domain + "Account/PermissionAdd.aspx");
                    }

                }


            }
            catch (Exception ex)
            {
                loga("Thêm Permission không thành công! ", "PERMISSION_ADD");
                ((Lapv)this.Master).MessageError = "Lấy dữ liệu bị lỗi" + ex.Message;
            }


        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {

        }
        void loadData()
        {
            try
            {
                List<permission> obj = null;

                using (lapvEntities db = new lapvEntities())
                {
                    obj = db.permissions.OrderBy(en => en.id).ToList();
                    if (obj != null)
                    {
                        dtgrid.DataSource = obj;
                        dtgrid.DataBind();
                    }
                    List<per_pages> lstpage = db.per_pages.ToList();
                    if (lstpage!=null) {
                        chkPermission.DataSource = lstpage;
                        chkPermission.DataTextField = "name";
                        chkPermission.DataValueField = "id";
                        chkPermission.DataBind();
                    }
                    


                    if (PMId != 0)
                    {
                        txtId.Enabled = false;
                        bt_luu.Text = "Lưu Permission";
                        permission objOld = db.permissions.Where(ec => ec.id == PMId).FirstOrDefault();
                        if (objOld != null)
                        {
                            txtId.Text =  objOld.id.ToString() ;
                            txtName.Text = objOld.name;
                            txtContent.Text = objOld.description;
                            txtId.Visible = true;


                            List<permission_pages> lstPerpage = db.permission_pages.ToList();
                           
                            short val = -1;
                            foreach (ListItem it in chkPermission.Items)
                            {
                                val = short.Parse(it.Value);
                                if (lstPerpage.Where(en => en.permission.id == val).Count() > 0)
                                    it.Selected = true;
                            }
                        }
                    }
                    else
                    {
                         bt_luu.Text = "Thêm Permission";
                         id.Visible = false;

                    }
                }

            }
            catch (Exception)
            {
                throw;
            }
       }
       private  void loga(string msg, string type)
        {
            int uid = 0;
            string uname = string.Empty;
            uid = ProviderAdmin.GetUsserId();
            if (Session["UserName"] != null)
                uname = Session["UserName"].ToString();
            ProviderAdmin.AddLog(uid, uname, msg, string.Empty, type);
        }
    }
}
